package pers.vic.sso.server.service.impl;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import pers.vic.boot.base.model.BaseResponse;
import pers.vic.boot.util.encrypt.PasswordUtils;
import pers.vic.sso.common.model.SsoUser;
import pers.vic.sso.server.service.SsoUserService;

import javax.annotation.Resource;

/**
 * 描述:
 *
 * @author Vic.xu
 * @date 2021-10-29 17:47
 */
@Service
public class SsoUserServiceImpl implements SsoUserService {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public BaseResponse<SsoUser> login(String username, String password) {
        SsoUser user = findUserByUsername(username);
        if (user == null) {
            return BaseResponse.error("不存在的用户");
        }

        boolean validatePassword = PasswordUtils.validatePassword(password, user.getPassword());
        if (!validatePassword) {
            return BaseResponse.error("用户名或密码错误");
        }
        return BaseResponse.success(user);
    }

    private SsoUser findUserByUsername(String username){
        String sql = "SELECT a.id, a.username, a.password  FROM sys_user a WHERE a.username = ? LIMIT 1 ";
        try{
            SsoUser user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<SsoUser>(SsoUser.class), username);
            return user;
        }catch (Exception e) {
            return null;
        }

    }
}
